package com.changgou.search.controller;

import com.changgou.entity.Page;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/search")
public class SearchController {

    @Autowired
    private SearchService searchService;


    /**
     * 根据查询条件返回数据
     * @param searchMap
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(@RequestParam Map<String, String> searchMap, Model model){

        //特殊字符处理
        this.handlerSearchMap(searchMap);
        //查询数据
        Map resultMap = searchService.search(searchMap);
        //封装返回结果
        model.addAttribute("result",resultMap);
        model.addAttribute("searchMap",searchMap);

        //封装分页数据并通过model返回
        Page<SkuInfo> page = new Page<>(
                Long.parseLong(String.valueOf(resultMap.get("total"))),
                Integer.parseInt(String.valueOf(resultMap.get("pageNum"))),
                Page.pageSize
        );
        model.addAttribute("page",page);

        //拼装url
        StringBuilder url = new StringBuilder("/search/list");
        if (searchMap != null && searchMap.size() > 0){
            //有查询条件
            url.append("?");

            for (String paramKey : searchMap.keySet()) {
                if (!"sortRule".equals(paramKey) && !"sortField".equals(paramKey) && !"pageNum".equals(paramKey)){
                    url.append(paramKey).append("=").append(searchMap.get(paramKey)).append("&");
                }
            }

            String urlString = url.toString();

            urlString = urlString.substring(0, urlString.length() - 1);
            model.addAttribute("url",urlString);
        }else {
            model.addAttribute("url",url);
        }

        //跳转页面
        return "search";
    }

    /**
     * 根据条件查询
     * @param searchMap
     * @return
     * @throws Exception
     */
    @GetMapping
    @ResponseBody
    public Map<String, Object> search(@RequestParam Map<String, String> searchMap) throws Exception {
        //特殊符号处理
        handlerSearchMap(searchMap);
        return searchService.search(searchMap);
    }

    /**
     * 查询条件中特殊字符处理
     * @param searchMap
     */
    public void handlerSearchMap(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();

        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().startsWith("spec_")){
                searchMap.put(entry.getKey(),entry.getValue().replace("+","%2B"));
            }
        }
    }

}
